package DAL.JDBC;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import DAL.Entites.Rank;

public class RankJDBC {
	Connection conn;

	String tableName = "ranks"; 

	public RankJDBC(Connection connection) {
		this.conn = connection;
	}
	
	public void insert(int GameId, int UserId, int RankNumber) {
		// this is for selecting db incase we do insert first
		// ((DriverManagerDataSource)dataSource).setUrl("jdbc:mysql://localhost:3306/TestData");
		String SQL = String.format("insert into %s values(null, %s, %s, %s)", tableName, UserId, GameId, RankNumber);
		
		try {
			Statement st = this.conn.createStatement();
			st.execute(SQL);
			st.close();
			System.out.println("Created Record");
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}
		return;
	}
	
	private Rank mapRow(ResultSet rs) throws SQLException {
		Rank rank = new Rank(
				rs.getInt("Id"), 
				rs.getInt("GameId"),
				rs.getInt("UserId"),
				rs.getInt("Rank"));
		System.out.println("mapRow");

		return rank;
	}
	
	public List<Rank> listRanksByGameId(int GameId) {
		List<Rank> ranks = new ArrayList<Rank>();
		String SQL = String.format("select * from %s where GameID = %s ", tableName, GameId);
		try {
			Statement st = conn.createStatement();
			for (ResultSet rs = st.executeQuery(SQL); rs.next();) {
				ranks.add(mapRow(rs));
			}
			st.close();
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}

		return ranks;
	}
	
	public Rank getRankForUserAndGame(int userId, int gameId)
	{
		Rank rank = null;
		
		String SQL = String.format("select * from %s where GameID = %s and UserId = %s", tableName, userId, gameId);
		try {
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(SQL); 
			rs.next();
			rank = mapRow(rs);
			st.close();
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}

		return rank;
	}
	
	public void update(Rank rank)
	{
		String SQL = String.format("update %s set Rank = %s where GameID = %s and UserId = %s",
				tableName, rank.getRankNumber(), rank.getGameId(),  rank.getUserId());
		try {
			Statement st = conn.createStatement();
			st.executeUpdate(SQL); 
			st.close();
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}

	}
}
